package com.magicode.screen.wxapi;

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.magicode.screen.AppConfig;
import com.magicode.screen.AppContext;
import com.magicode.screen.R;
import com.magicode.screen.api.ApiHttpClient;
import com.magicode.screen.api.remote.MgcApi;
import com.magicode.screen.bean.User;
import com.magicode.screen.bean.UserEntity;
import com.magicode.screen.react.activity.MainTabReactActivity;
import com.magicode.screen.util.HttpInternet;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Window;
import android.widget.Toast;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.http.HttpConfig;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler{

	// IWXAPI 是第三方app和微信通信的openapi接口
	private IWXAPI api;
	public static String WEXIN_SCOPE = "";// 这里填的snsapi_userinfo，用snsapi_base提示没权限。
	public static String WEIXIN_STATE = "";// 用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验。
	public Context context;
	public static final int REQUEST_CODE_INIT = 0;
	private final int requestCode = REQUEST_CODE_INIT;
	private static final String BUNDLE_KEY_REQUEST_CODE = "BUNDLE_KEY_REQUEST_CODE";
	private ReactInstanceManager mReactInstanceManager = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		context=this;
		if(api==null){
			api=WXAPIFactory.createWXAPI(this,AppConfig.APP_WX_KEY, false);
			api.registerApp(AppConfig.APP_WX_KEY);
		}

		api.handleIntent(getIntent(), this);
		handleIntent(getIntent());
	}
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		api.handleIntent(intent, this);
	}

	private void handleIntent(Intent intent) {
		SendAuth.Resp resp = new SendAuth.Resp(intent.getExtras());
		if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
			//用户同意
		}
	}
	// 微信发送请求到第三方应用时，会回调到该方法
	@Override
	public void onReq(BaseReq req) {
		switch (req.getType()) {
			case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
				goToGetMsg();
				break;
			case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
				goToShowMsg((ShowMessageFromWX.Req) req);
				break;
			default:
				break;
		}
	}

	// 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
	@Override
	public void onResp(BaseResp resp) {
		String result = "";

		switch (resp.errCode) {
			case BaseResp.ErrCode.ERR_OK:
				result ="授权成功";
				switch (resp.getType()) {
					case ConstantsAPI.COMMAND_SENDAUTH:
						//登录回调,处理登录成功的逻辑
						SendAuth.Resp sendResp = (SendAuth.Resp) resp;
						WEXIN_SCOPE = sendResp.code;
						WEIXIN_STATE= sendResp.state;
						/**获得微信用户信息**/
						loadWXUserInfo();
						break;
					case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
						//分享回调,处理分享成功后的逻辑
						result="分享成功";
						finish();
						break;
					default:
						break;
				}
				break;
			case BaseResp.ErrCode.ERR_USER_CANCEL:
				result = "授权取消";
				finish();
				break;
			case BaseResp.ErrCode.ERR_AUTH_DENIED:
				result = "授权被拒绝";
				finish();
				break;
			default:
				result ="授权返回";
				finish();
				break;
		}

		Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	}

	/* 类级的内部类，也就是静态的成员式内部类，该内部类的实例与外部类的实例 没有绑定的关系，而且只有被调用到时才会装载，从而实现了延迟加载 */
	private static class SingTonHolder {
		/* 静态初始化器，由JVM来保证线程安全 */
		private static WXEntryActivity instance = new WXEntryActivity();
	}

	/* 该单例实现了延迟加载和线程安全 */

	public static WXEntryActivity getInstance() {
		return SingTonHolder.instance;
	}
	/**
	 *
	 * @methods: 获得微信用户信息
	 */
	private void loadWXUserInfo() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String accessTokenUrl =
						"https://api.weixin.qq.com/sns/oauth2/access_token?appid="
								+ AppConfig.APP_WX_KEY
								+ "&secret="
								+ AppConfig.APP_WX_Secret
								+ "&code="
								+ WEXIN_SCOPE + "&grant_type=authorization_code";
				// String tokenResult = ApiClient.httpsGet(accessTokenUrl);
				String tokenResult= null;
				try {
					tokenResult = HttpInternet.sendHttpClientByJson(accessTokenUrl, "", "GET");
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (null != tokenResult) {
					JSONObject tokenObj;
					try {
						tokenObj = new JSONObject(tokenResult);
						String accessToken = tokenObj.optString("access_token");
						String openId = tokenObj.optString("openid");
						String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
								+ accessToken + "&openid=" + openId;
						// String wxUserInfo = ApiClient.httpsGet(userUrl);
						String wxUserInfo = null;
						try {
							wxUserInfo = HttpInternet.sendHttpClientByJson(userUrl, "", "GET");
						} catch (Exception e) {
							e.printStackTrace();
						}
						if (null != wxUserInfo) {
							JSONObject userObj = new JSONObject(wxUserInfo);
							String openid = userObj.optString("openid");
							String nickname = userObj.optString("nickname");
							String sex = "1".equals(userObj.optString("sex"))?"Male":"Female";
							String province = userObj.optString("province");
							String country = userObj.optString("country");
							String headimgurl = userObj.optString("headimgurl");
							String unionid = userObj.optString("unionid");
							MgcApi.outerLogin(openid, nickname, sex, province, country, unionid, headimgurl, mHandler);
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			try {
				AsyncHttpClient client = ApiHttpClient.getHttpClient();
				HttpContext httpContext = client.getHttpContext();
				CookieStore cookies = (CookieStore) httpContext
						.getAttribute(ClientContext.COOKIE_STORE);
				if (cookies != null) {
					String tmpcookies = "";
					for (Cookie c : cookies.getCookies()) {
						tmpcookies += (c.getName() + "=" + c.getValue()) + ";";
					}
					AppContext.getInstance().setProperty(AppConfig.CONF_COOKIE,
							tmpcookies);
					ApiHttpClient.setCookie(ApiHttpClient.getCookie(AppContext
							.getInstance()));
					HttpConfig.sCookie = tmpcookies;
				}
				ObjectMapper mapper = new ObjectMapper();
				UserEntity userEntity = mapper.readValue(arg2, UserEntity.class);
				if (userEntity.isOk()) {
					// 保存登录信息
					if (null!=userEntity.getEntity() && null!=userEntity.getEntity().getUserId()) {
						User user=userEntity.getEntity();
						AppContext.getInstance().saveUserInfo(user);
						sendEventForReact();
						Toast.makeText(getBaseContext(), "你好，" + user.getUserName(), Toast.LENGTH_LONG).show();
						finish();
					}
				} else {
					AppContext.getInstance().cleanLoginInfo();
					Toast.makeText(context,userEntity.getMessage(), Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
				onFailure(arg0, arg1, arg2, e);
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							  Throwable arg3) {
//			AppContext.showToast(R.string.tip_error_for_network);
		}
	};
	private void sendEventForReact() {
		ReactNativeHost rnh = AppContext.getInstance().getReactNativeHost();
		if (null != rnh) {
			mReactInstanceManager = rnh.getReactInstanceManager();
		}
		WritableMap params = Arguments.createMap();
		params.putString("login", "true");
		sendEvent(mReactInstanceManager.getCurrentReactContext(), "thirdLogin", params);
	}
	private void handleLoginSuccess() {
		Intent data = new Intent();
		data.putExtra(BUNDLE_KEY_REQUEST_CODE, requestCode);
		setResult(RESULT_OK, data);
		this.sendBroadcast(new Intent(com.magicode.screen.bean.Constants.INTENT_ACTION_USER_CHANGE));
		Intent intent=new Intent(this,MainTabReactActivity.class);  //方法1;
		startActivity(intent);
		overridePendingTransition(R.anim.anim_right_get_into, R.anim.anim_left_sign_out);
	}

	private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
		reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
				.emit(eventName, params);
	}
	private void goToGetMsg() {
	}

	private void goToShowMsg(ShowMessageFromWX.Req showReq) {
		WXMediaMessage wxMsg = showReq.message;
		WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;

		StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
		msg.append("description: ");
		msg.append(wxMsg.description);
		msg.append("\n");
		msg.append("extInfo: ");
		msg.append(obj.extInfo);
		msg.append("\n");
		msg.append("filePath: ");
		msg.append(obj.filePath);
	}
}